package com.sparrow.common.excel.handler;

import com.sparrow.common.excel.bean.ExcelCol;
import com.sparrow.common.excel.bean.ExcelRow;
import com.sparrow.common.excel.bean.ExcelSheet;
import org.apache.poi.ss.util.CellAddress;
import org.apache.poi.ss.util.CellReference;
import org.apache.poi.xssf.eventusermodel.XSSFSheetXMLHandler;
import org.apache.poi.xssf.usermodel.XSSFComment;
import java.util.ArrayList;
import java.util.List;

public class SheetDataHandler implements XSSFSheetXMLHandler.SheetContentsHandler {

    private ExcelSheet sheet;


    private int curRow = -1;

    private int curCol = -1;

    private List<ExcelCol> cols = new ArrayList<>();

    public SheetDataHandler(ExcelSheet sheet) {
        this.sheet = sheet;
    }

    @Override
    public void startRow(int rowNum) {
        if (curRow != rowNum) {
            this.curRow = rowNum;
            this.curCol = -1;
            this.cols.clear();
//            System.out.println("开始处理 row:" + curRow);
        }
    }

    @Override
    public void endRow(int rowNum) {
        ExcelRow row = new ExcelRow(this.curRow, this.cols.toArray(new ExcelCol[0]));
        sheet.addRow(row);
    }

    @Override
    public void cell(String cellReference, String formattedValue, XSSFComment comment) {
        if (cellReference == null) {
            cellReference = new CellAddress(curRow, curCol).formatAsString();
        }
        int thisCol = (new CellReference(cellReference)).getCol();
        this.curCol = thisCol;

        int missedCols = thisCol - curCol - 1;
        for (int i = 0; i< missedCols; i++) {
            //没有内容的
        }
        ExcelCol col = new ExcelCol(this.curRow, this.curCol, formattedValue);
        this.cols.add(col);
//        System.out.println("单元格 row:" + this.curRow + " col:" + thisCol + " val:" + formattedValue);
    }
}
